import React,{useContext,useReducer}from 'react';

const initialState={
    a:'1111',
    b:'2222'
}

const reducer=(prevState,action)=>{
    let newState={...prevState}
    switch(action.type){
        case 'change-child2':
            newState.a=action.value
            return newState;
        case 'change-child3':
            newState.b=action.value;
            return newState
        default:
            return prevState
    }
}

const GlobalContext=React.createContext()
export default function App(){
    const [state,dispatch]=useReducer(reducer,initialState)
    return (
        <GlobalContext.Provider value={{
            state,
            dispatch
        }}>
            <Child1/>
            <Child2/>
            <Child3/>
        </GlobalContext.Provider>
    );
}

function Child1(){
    const {dispatch}=useContext(GlobalContext)
    return <div>
        <button onClick={()=>{
            dispatch({
                type:'change-child2',
                value:'child2我改了哦'
            })
        }}>改child2</button>
        <button onClick={()=>{
            dispatch({
                type:'change-child3',
                value:'child3我改了哦'
            })
        }}>改child3</button>
    </div>
}

function Child2(){
    const {state}=useContext(GlobalContext)
    return <div>
        {state.a}
    </div>
}

function Child3(){
    const {state}=useContext(GlobalContext)
    return <div>
        {state.b}
    </div>
}